#include <QtGui>
#include <QtOpenGL>
#include "../dataengine/VibTerrainFileManager.h"

#include "mainwidget.h"

// SLOTS ------------->>

void MainWidget::speciesChanged(slotsdata::SpeciesProperties properties)
{
	makeCurrent();

	currentSpecies = properties;
	std::map<QString, geom::PolyObject>::const_iterator it = currentSpecies.begin();
	std::map<QString, geom::PolyObject>::const_iterator end = currentSpecies.end();

	m_treeRenderers.clear(); // This could be done a little bit better to avoid removing renderers of models that will not be changed
	m_treeImpostors.clear();

	for(;it!=end;++it)
	{	
		int numModels = it->second.getNumberOfModels();
		for(int i=0; i<numModels;++i)
		{
			RendererInfo r;
			r.speciesFile = it->first;
			r.baseScale = properties.baseScale();
			r.fileModel = i;
			const geom::PolyModel & model = it->second.getModel(i);
			m_treeRenderers.insert(std::pair<RendererInfo,glutil::ModelRenderer>(r, glutil::ModelRenderer(model,properties.baseScale())));
			m_treeImpostors.insert(std::pair<RendererInfo,glutil::Impostor>(r, glutil::Impostor(model, 512,properties.baseScale())));
		}
	}
	reconstructForestFromData();
	updateGL();
}


void MainWidget::imagePropertiesChanged(slotsdata::ImageProperties properties)
{
	m_camera->setFOV(properties.cameraFOV());
	m_postProcess->setImageProperties(properties);
	updateGL();
}


void MainWidget::groundDataChanged(slotsdata::GroundProperties properties)
{
	static std::string lastFile = "";
	if(properties.filename() != lastFile)
	{
		dataengine::VibTerrainFileManager vibLoader(properties.filename());
		if(!vibLoader.canLoadFile())
		{
			qDebug()<<"File "<<properties.filename().c_str()<<" could not be loaded as a terrain";
			return;
		}
		this->m_currentTerrain = vibLoader.loadFile();
		this->m_terrainRenderer.reset(new glutil::TerrainRenderer(&m_currentTerrain));
		lastFile = properties.filename();
	}
	m_currentTerrain.setDisplacement(properties.displacement());
	m_currentTerrain.setScale(properties.scale());
	m_currentTerrain.setBaseColor(properties.baseColor().dx,properties.baseColor().dy,properties.baseColor().dz);

	reconstructForestFromData();
	m_grass->updateTerrain(this->m_currentTerrain);
	updateGL();
}

void MainWidget::skyDataChanged(slotsdata::SkyProperties properties)
{
	static bool firstTime = true;

	m_sky.setSkyProperties(properties);
	if(firstTime)
		firstTime = false;
	else
		updateGL();

}


// << ------------!SLOTS

